﻿using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI
{
    /// <summary>
    /// 父级控制器
    /// </summary>
    public class BaseController: ControllerBase
    {
        private readonly IWebHostEnvironment environment;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="environment"></param>
        public BaseController(IWebHostEnvironment environment)
        {
            this.environment = environment;
        }

        /// <summary>
        /// 获取当前登录人Id
        /// </summary>
        /// <returns></returns>
        protected internal long BaseGetNowUserId()
        {
            string nowuserid = HttpContext.User.FindFirstValue("Id");
            return Convert.ToInt64(nowuserid);
        }

        /// <summary>
        /// 获取当前登录人姓名
        /// </summary>
        /// <returns></returns>
        protected internal string BaseGetNowUserName()
        {
            return HttpContext.User.FindFirstValue("UserName");
        }

        /// <summary>
        /// 获取当前登录人真实姓名
        /// </summary>
        /// <returns></returns>
        protected internal string BaseGetNowUserRealName()
        {
            return HttpContext.User.FindFirstValue("RealName");
        }

        /// <summary>
        /// 获取请求IP
        /// </summary>
        /// <returns></returns>
        protected internal string BaseGetRequestIp()
        {
            var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
            if (remoteIpAddress != null)
                return remoteIpAddress.ToString();
            return "UNKNOWN";
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        protected internal async Task<IActionResult> BaseUploadFile(IFormFile file)
        {
            // 检查文件是否为空
            if (file == null || file.Length == 0)
            {
                return BadRequest("没有选择文件或文件为空.");
            }
            // 检查文件类型
            string fileExtension = Path.GetExtension(file.FileName).ToLower();
            if (fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".gif" && fileExtension != ".jfif")
            {
                return BadRequest("只允许上传 .jpg, .png 和 .gif 和.jfif 格式的文件.");
            }
            // 检查文件大小
            if (file.Length > 200 * 1024) // 单位为字节
            {
                return BadRequest("上传的图片必须小于 200KB.");
            }
            try
            {
                // 获取保存文件的根路径
                string uploadsFolder = Path.Combine(environment.WebRootPath, "file");

                // 创建文件夹（如果不存在）
                Directory.CreateDirectory(uploadsFolder);

                // 创建以当前日期命名的文件夹
                string currentDateFolder = DateTime.Now.ToString("yyyyMMdd");
                string folderPath = Path.Combine(uploadsFolder, currentDateFolder);
                Directory.CreateDirectory(folderPath);

                // 生成以当前时间命名的文件名
                string currentTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                string fileExtension1 = Path.GetExtension(file.FileName).ToLower();
                string fileName = $"{currentTime}{fileExtension1}";

                // 保存文件到指定路径
                string filePath = Path.Combine(folderPath, fileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                return Ok("http://localhost:5236/file/" + currentDateFolder + "/" + fileName);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"文件上传失败：{ex.Message}");
            }
        }

        /// <summary>
        /// Excel导出
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        protected internal IActionResult BaseDowLoadExcel<T>(List<T> list)
        {
            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(list);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"{Guid.NewGuid()}.xlsx"
            };
        }
    }
}
